package club.gggd.mimotion.util;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @Description
 * @Author srx
 * @date 2022/4/7 14:34
 */
@Slf4j
@Component
public class FileUtil {

    public static String name;

    public static String path;

    @Value("${file.name}")
    public void setName(String name) {
        FileUtil.name = name;
    }

    @Value("${file.path}")
    public void setPath(String path) {
        FileUtil.path = path;
    }

    /**
     * 删除key
     * @param key
     */
    public static void remove(String key){
        log.info("正在从存储文件中删除：" + key);
        Properties properties = read();
        properties.remove(key);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path + name);
            properties.store(out, "remove:" + key);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 添加key，value至properties
     * @param key
     * @param value
     */
    public static void add(String key, String value){
        log.info("正在从存储文件中添加：" + key);
        Properties properties = read();
        properties.put(key, value);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path + name);
            properties.store(out, "add:" + key);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取properties
     * @return
     */
    private static Properties read(){
        Properties properties = new Properties();
        FileInputStream in = null;
        try {
            in = new FileInputStream(path + name);
            properties.load(in);
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return properties;
    }

}
